package com.promis.crypto.symmetric;

import com.promis.crypto.KeyCipher;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;


public class SymmetrickKeyCipher extends KeyCipher {
	
	public SymmetrickKeyCipher(String keyAlgorithm, String cipherAlgorithm) {
		super(keyAlgorithm, cipherAlgorithm);
	}

	public SecretKey createSecretKey(int keySize) throws NoSuchAlgorithmException {
		KeyGenerator keyGenerator = KeyGenerator.getInstance(keyAlgorithm);
		keyGenerator.init(keySize);
		return keyGenerator.generateKey();
	}
	
	public SecretKey toSecretKey(byte[] secretKey) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException {
	    return new SecretKeySpec(secretKey, keyAlgorithm);
	}
	
	public static byte[] toSecretKey(SecretKey secretKey) {
		return secretKey.getEncoded();
	}
	
	public byte[] encrypt(byte[] data, SecretKey secretKey) throws Exception {  
	    return cipher(Cipher.ENCRYPT_MODE, data, secretKey);
	}
	
	public byte[] decrypt(byte[] data, SecretKey secretKey) throws Exception {
		return cipher(Cipher.DECRYPT_MODE, data, secretKey);
	}
}
